<script lang="ts" setup>
	import { ref, onMounted, computed } from 'vue';
	import { createAppoint, getQuestions, getAdvisorys, getAdvisorysByTime } from '@/api/psychology/appointment.js'
	import { getUserList } from '@/api/school.js'
	import { userInfo } from '@/store/Pinia/userInfo.js'
	import TnPopup from '../../../node_modules/@tuniao/tnui-vue3-uniapp/components/popup/src/popup.vue'
	import { isInArray } from '@/common/common.ts'


	const props = defineProps({
		id: {
			type: [String, Number],
			default: ''
		}
	})

	const cates = ["选择时间预约", "选择老师预约"]
	const stateList = [1, 99, 100]

	let curNow = ref('1');
	let timeShow = ref(true);
	let teachers = ref<any[]>([]);
	let theTeacher = ref({});
	let allQuestions = ref({});
	let time = ref('');
	let number = ref('');
	let an1 = ref();
	let an2 = ref();
	let an3 = ref();
	const answers = ref<any[]>([]);
	const littleShowPopup = ref(false)
	const showPopup = ref(false)
	let fullDate = ref();
	const userInfoModel = userInfo()

	const year = ref(0)

	const getDate = computed(() => {
		return function (time) {
			const year = time.getFullYear(); // 获取年份
			const month = String(time.getMonth() + 1).padStart(2, '0'); // 获取月份，并补零
			const day = String(time.getDate()).padStart(2, '0'); // 获取日期，并补零
			return `${year}-${month}-${day}`
		}
	})

	let currentDate = new Date();
	let fiveDaysLater = new Date();
	onMounted(() => {

		fiveDaysLater.setDate(currentDate.getDate() + 6);

		year.value = currentDate.getFullYear(); // 获取年份
		const month = String(currentDate.getMonth() + 1).padStart(2, '0'); // 获取月份，并补零
		const day = String(currentDate.getDate()).padStart(2, '0'); // 获取日期，并补零
		fullDate.value = `${year.value}-${month}-${day}`;
		getCnTeacher()
		appoint()

	});

	const getCnTeacher = () => {
		let item = {
			"sysRole": "cn_user",
			'id': props.id
		}
		getUserList(item).then((res) => {
			timeShow.value = false;
			res.data.data.map((item) => {
				// teachers.value = []
				theTeacher.value = item
			})
			console.log('getUserListgetUserList', theTeacher.value)
		})
	}


	const getAllQuestions = () => {
		let item = {
			problemState: "1"
		}
		getQuestions(item).then((res) => {
			allQuestions.value = res.data.data
			console.log('allQuestions:', allQuestions.value);
		}).catch((error) => {
			console.error('error:', error);
		})
	};

	// 自动保存
	const exit = () => {
		littleShowPopup.value = true;

	}
	const goBack = () => {
		littleShowPopup.value = false;
	}

	interface answersList {
		an1 ?: String,
		an2 ?: String,
		an3 ?: String,
	}

	interface createItem {
		"cnId" ?: String | number,
		"stuId" ?: String,
		"consRoomId" ?: String,
		"reservationDate" ?: String,
		"reservationEndTime" ?: String,
		"reservationStartTime" ?: String,
		"consAdvisoryState" ?: String,
		"stuPhone" ?: String,
		"problemList" ?: any,
		"consCnDutyId" ?: String | number
	}

	const createItem = ref<createItem>({})
	const answersObj = ref<answersList>({})


	const no = () => {
		selectTimeId.value = null

		littleShowPopup.value = false;
		showPopup.value = false;
		createItem.value = {}


	}

	const objReduce = computed(() => {//将对象列表中，每个对象的某个属性提出来作为key值，并且重复的合并
		return function (obj, keyName) {
			let groupedObject = obj.reduce((accumulator, currentObject) => {
				const key = currentObject[keyName];
				// 如果当前key还不存在，创建一个新数组
				if (!accumulator[key]) {
					accumulator[key] = [];
				}
				// 将当前对象添加到对应的数组中
				accumulator[key].push(currentObject);
				return accumulator;
			}, {});
			return groupedObject;
		}
	})

	const appoint = () => {

		if (curNow.value == '1') {
			let itemByTh = {
				"cnId": props.id,
				"workDateStart": getDate.value(currentDate),
				"workDateEnd": getDate.value(fiveDaysLater),
			}
			getAdvisorysByTime(itemByTh).then((res) => {
				schedulingList.value = objReduce.value(res.data.data, 'workDate')
				console.log('appointappointappointappointappointappoint', schedulingList.value)
			})
		}
	}


	const selectDate = ref('')
	const sectionChange = (index : any) => {
		curNow.value = index;
		console.log('sectionChangeindex', index)
		if (index == 0) {
			timeShow.value = true;
			uni.navigateTo({
				url: '/pages/appointment/index'
			})
		} else {


		}
	}

	const confirm = (date ?: any) => {
		let item = {
			"cnId": selectItem.value.cnId,
			"reservationStartTime": selectItem.value.workStartTime,
			"reservationEndTime": selectItem.value.workEndTime,
			"consAdvisoryState": 1
		}

		getAdvisorys(item).then((res) => {
			if (res.data.success) {
				if (res.data.data < 1) {
					answers.value = [];
					answers.value.push({ name: allQuestions.value[0]?.name, value: an1.value });
					answers.value.push({ name: allQuestions.value[1]?.name, value: an2.value });
					answers.value.push({ name: allQuestions.value[2]?.name, value: an3.value });
					createItem.value.cnId = selectItem.value?.cnId
					createItem.value.stuId = userInfoModel.data.id
					createItem.value.consRoomId = selectItem.value?.consRoom?.id
					createItem.value.reservationDate = selectItem.value?.workDate
					createItem.value.reservationStartTime = selectItem.value?.workStartTime
					createItem.value.reservationEndTime = selectItem.value?.workEndTime
					createItem.value.consAdvisoryState = '1'
					createItem.value.consCnDutyId = selectItem.value?.id
					createItem.value.problemList = allQuestions.value

					console.log('createItem.value', createItem.value)
					createAppoint(createItem.value).then((res) => {
						if (res.data.success) {
							uni.showToast({
								title: '预约成功'
							})
						}
					})
				} else {
					uni.showToast({
						icon: 'none',
						title: '预约失败，该时段已被预约'
					})
				}
			}
		})
	}


	let isEmpty = computed<boolean>(() => {
		return teachers.value.every((teacher : any) => teacher.date !== fullDate.value);
	});


	// const getTime = computed(() => {
	// 	return function (time) {
	// 		if (time != undefined) {
	// 			var dateObject = new Date(time);
	// 			var timeString = dateObject.toLocaleTimeString('en-US', { hour12: false });

	// 			return `${timeString}`
	// 		} else {
	// 			return time
	// 		}
	// 	}
	// })


	const getTime = computed(() => {
		return function (time) {
			if (time != void 0) {
				var dateObject = new Date(time);

				var timeString = dateObject.toLocaleTimeString('zh', { hour12: false });

				return `${dateObject.getHours()}:${(dateObject.getMinutes() < 10 ? '0' : '') + dateObject.getMinutes()}`
			} else {
				return time
			}
		}
	})

	const formmatTime = computed(() => {//将2023-12-14转换成12/14
		return function (tiem) {
			let dateString = tiem;

			// 创建日期对象
			let dateObject = new Date(dateString);

			// 提取月份和日期
			let month = (dateObject.getMonth() + 1).toString().padStart(2, '0'); // 月份是从0开始，所以需要加1
			let day = dateObject.getDate().toString().padStart(2, '0');

			// 创建新的格式
			let newFormat = `${month}/${day}`;

			return newFormat
		}
	})


	const schedulingList = ref([])


	const selectTimeId = ref(0)
	const selectTimeValue = ref('')
	const selectItem = ref({})
	const selectTime = (e) => {
		console.log('selectTimeselectTimeselectTime', e)
		selectTimeId.value = e.id
		selectItem.value = e
		uni.navigateTo({
			url: '/pages/appointment/apmForm/apmForm?id=' + e.id
		})

	}

	const back = () => {
		uni.navigateBack()
	}
	const timer = ref(null)
	const handleEnd = () => {
		timer.value.resetTime()
	}
</script>

<template>
	<articleTable ref="timer"></articleTable>
	<img :src="'@/../static/img/appoint/appoint-bg.svg'"
		style="opacity: 0.2;width: 45%;position: absolute;top: 50%;right: 0;" />
	<Navigator :fixed="true" background-color="transparent" status-bar title="心理预约" customLeft
		style="position: absolute;">
	</Navigator>
	<view @touchend="handleEnd" class="wh100p bg0078BB-003E94 flex-column " style="justify-content: center; align-items: center;">

		<view class="w100p h100p flex-column" style="padding:1% 2%;box-sizing: border-box;z-index:2;">
			<view class="wh100p flex">
				<view class="flex-column select-body" style="height: 100%;">
					<view class=" consultant-tabs">
						<view style="width:120px;">
							<u-button class="custom-style" text="返回" icon="arrow-left" @click="back"></u-button>

						</view>
					</view>
					<view class="wh100p  consultant-details-box flex">
						<view class="consultant-info-box flex-column" style="align-items: center;">
							<view class="avatar-box">
								<img :src="theTeacher?.avatar??'@/../../static/img/bigavatar.png'"
									style="width: 128rpx;height: 128rpx;border-radius: 50%;" mode="aspectFill"/>
							</view>
							<text class="cnUser-name">姓名:{{theTeacher?.realName}}</text>
							<text class="cnUser-phone">电话:{{theTeacher?.phone}}</text>
							<text class="cnUser-email">邮箱:{{theTeacher?.email}}</text>
							<view class="intro-content mt10">
								<text
									style="min-width: 100%;">{{theTeacher?.remark!=null && theTeacher?.remark!=""?theTeacher?.remark:'如果你有需要,我一直都在。'}}</text>
							</view>
						</view>
						<view class="details-right h100p" style="height: 98%;padding: 20px;box-sizing: border-box;">
							<view class="time-box wh100p" style="height:100%;overflow: scroll;">
								<view class="details-year">{{getDate(currentDate)}}</view>
								<view class="w100p flex-column" style="margin-top: 20rpx;">

									<view style="flex-wrap: wrap;width: 100%;padding: 0 30px;" class=" ">
										<view v-for="(items,key) of schedulingList" class="scheduling-item">
											<text class="scheduling-date">
												{{formmatTime(key)}}
											</text>
											<view class="date-scheduling">
												<view v-for="(item,index) of items"
													class=" bg63B0FF flex-between column-center "
													style="width: 40%;padding:30rpx;margin: 0rpx 10px;border-radius: 10rpx;height: 66px;"
													@click="isInArray(stateList,item.consCnDutyState)? '' : selectTime(item)">
													<view class="flex-column" style="font-size: 18px;">
														<view class="flex column-center">
															{{getTime(item?.workStartTime)}}<text
																style="padding: 0 5px;">--</text>{{getTime(item?.workEndTime)}}
														</view>
														<view>地址：{{item?.consRoom?.name}}
														</view>
													</view>
													<view>
														<view v-if="isInArray(stateList,item.consCnDutyState)">
															<view>
																<u-tag text="暂无名额" bgColor="#bababa"
																	borderColor="#bababa" size="large">
																</u-tag>
															</view>
														</view>
														<view v-else>
															<view><u-tag text="点击选择" plain @click="selectTime(item)">
																</u-tag>
															</view>
														</view>
													</view>
												</view>
											</view>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>


				<TnPopup v-model="showPopup" :overlay-closeable="false" width="50%" height="70vh" :z-index="20">
					<view style="display: flex;justify-content: space-between;margin-top: 20rpx;position: relative;">
						<veiw class="flex-center" style="flex: 1;">
							<h1 style="text-align: center;">预约详情</h1>
						</veiw>
						<view class=" absolute w100p flex-end" style="padding-right: 30rpx;box-sizing: border-box;">
							<u-icon @click="yes" name="close" color="#2979ff" size="28"></u-icon>
						</view>
					</view>
					<view style="padding: 60rpx;overflow: scroll;width: 100%;height: 100%;box-sizing: border-box;">
						<view class="tn-p-lg" style="overflow: scroll;width: 100%;">
							<view
								style="display: flex;flex-direction: column; border:3rpx solid rgb(226, 230, 234);padding:1rem;border-radius: 50rpx;font-size: 1.2rem;margin-bottom: 50rpx;">
								<view style="padding: 20rpx;">
									<view style="display: flex;justify-content:flex-start">
										<view class="mr20">
											<img :src="theTeacher?.avatar??'@/../../static/img/bigavatar.png'"
												style="width: 100rpx;height: 100rpx;border-radius: 50rpx;" mode="aspectFill" />
											<!-- <img class="avatar" :src="'@/../../static/img/bigavatar.png'"
												mode="aspectFill" /> -->
										</view>
										<view>
											<view><text style="font-weight: bold;">姓名：</text> {{theTeacher?.realName}}
											</view>
											<view>如果你有需要，我一直都在</view>
										</view>
									</view>

									<view style="margin-top: 30rpx;"><text style="font-weight: bold;">咨询地点：</text>
										<text>{{selectItem?.consRoom?.name??'待定'}}</text>
									</view>

								</view>
							</view>

							<hr />

							<view
								style="margin-top:30rpx;font-size: 1.2rem;padding: 20rpx;border:3rpx solid rgb(226, 230, 234);border-radius: 50rpx;">
								<view style="display: flex;align-items: center;">
									<svg t="1702521895211" class="icon" viewBox="0 0 1024 1024" version="1.1"
										xmlns="http://www.w3.org/2000/svg" p-id="2766" width="32" height="48">
										<path
											d="M512 901.76a352 352 0 1 1 352-352A352.426667 352.426667 0 0 1 512 901.76z m0-640a288 288 0 1 0 288 288A288.213333 288.213333 0 0 0 512 261.76z"
											fill="#0091FD" p-id="2767"></path>
										<path
											d="M809.386667 401.92a31.786667 31.786667 0 0 1-25.6-50.986667 105.173333 105.173333 0 1 0-168.96-125.226666 32.213333 32.213333 0 0 1-44.8 6.613333 31.786667 31.786667 0 0 1-6.613334-44.8 169.173333 169.173333 0 0 1 271.786667 201.6 32.426667 32.426667 0 0 1-25.813333 12.8zM219.093333 401.92a32.213333 32.213333 0 0 1-25.813333-12.8A169.173333 169.173333 0 1 1 465.066667 187.52a32 32 0 1 1-51.413334 38.186667 105.173333 105.173333 0 1 0-168.96 125.226666 32.213333 32.213333 0 0 1-6.613333 44.8 31.573333 31.573333 0 0 1-18.986667 6.186667z"
											fill="#F7B500" p-id="2768"></path>
										<path
											d="M219.093333 401.92a31.573333 31.573333 0 0 0 18.986667-6.186667 32.213333 32.213333 0 0 0 6.613333-44.8 106.666667 106.666667 0 0 1-10.24-17.066666 360.96 360.96 0 0 0-37.333333 59.306666 31.786667 31.786667 0 0 0 21.973333 8.746667zM413.653333 225.706667a32 32 0 0 0 56.96-25.386667 364.586667 364.586667 0 0 0-66.773333 14.506667 96.213333 96.213333 0 0 1 9.813333 10.88z"
											fill="#006700" p-id="2769"></path>
										<path
											d="M490.666667 631.253333a32 32 0 0 1-32-32V426.666667a32 32 0 0 1 64 0v171.946666a32 32 0 0 1-32 32.64z"
											fill="#F7B500" p-id="2770"></path>
										<path
											d="M490.666667 631.253333a32.213333 32.213333 0 0 1-22.613334-9.386666 31.786667 31.786667 0 0 1 0-45.226667l120.32-120.32a32 32 0 0 1 45.226667 45.226667l-120.32 120.32a32.213333 32.213333 0 0 1-22.613333 9.386666z"
											fill="#F7B500" p-id="2771"></path>
										<path
											d="M791.893333 337.28a88.533333 88.533333 0 0 1-8.106666 13.653333 31.786667 31.786667 0 0 0 44.373333 44.8 356.693333 356.693333 0 0 0-36.266667-58.453333zM570.026667 232.32a32.213333 32.213333 0 0 0 44.8-6.613333 74.026667 74.026667 0 0 1 8.533333-9.6 354.56 354.56 0 0 0-65.706667-15.146667 32.213333 32.213333 0 0 0 12.373334 31.36z"
											fill="#006700" p-id="2772"></path>
									</svg>
									<span
										style="line-height:80rpx;font-weight: bold;color: darkgray;text-indent: 1rem;">
										具体时段：
									</span>
									<view style="text-indent: 2rem;">
										{{getTime(selectItem?.workStartTime)}}--{{getTime(selectItem?.workEndTime)}}
									</view>
								</view>
								<hr style="width: 90%;margin: auto;" />
								<view style="display: flex;height: 80rpx;align-items: center;">
									<svg t="1702522237518" class="icon" viewBox="0 0 1024 1024" version="1.1"
										xmlns="http://www.w3.org/2000/svg" p-id="4848" width="32" height="32">
										<path
											d="M687.104 940.032c-30.208 0-52.224-4.096-60.928-6.144-38.912-2.048-91.136-27.648-128.512-49.664-53.248-30.72-112.64-73.728-166.4-120.832-61.44-53.248-115.2-111.616-156.672-168.448-49.152-67.584-80.896-133.632-93.696-196.096-19.968-97.792-9.216-174.08 32.256-226.816 48.64-62.464 120.832-66.048 123.904-66.56h2.048c3.072 0 31.232 1.024 65.024 13.824 46.592 17.92 81.408 50.176 100.352 93.696 14.848 33.792 16.384 65.024 4.608 96.256-9.728 25.6-26.112 46.08-42.496 66.048-14.336 17.408-27.648 34.304-34.816 52.224 0 1.536 0 9.728 11.776 29.696 9.728 16.896 25.6 37.376 45.056 58.88 35.328 39.424 83.456 81.92 127.488 113.664 54.272 38.912 84.48 48.64 94.208 48.128 53.248-2.048 116.736-51.2 135.168-66.048 13.824-11.264 31.232-16.896 49.152-15.872 71.68 4.608 120.32 28.16 144.384 69.12 14.848 25.088 18.944 56.832 12.8 90.624-4.608 24.064-12.8 40.96-13.824 43.008l-0.512 1.536-1.024 1.536c-59.904 94.208-142.336 125.44-200.192 134.656-17.92 2.56-34.816 3.584-49.152 3.584z m-49.152-66.048c1.536 0.512 40.96 9.728 91.136 1.536 65.024-10.752 117.248-46.08 154.624-104.96 6.144-13.824 16.896-49.664 2.048-74.752-16.384-27.648-60.416-36.352-94.72-38.912-2.56 0-4.608 0.512-6.656 2.048-34.816 28.672-103.936 77.312-171.52 80.384h-2.56c-44.544 0-108.544-42.496-154.624-78.336-59.904-46.592-115.712-102.4-148.992-148.992-31.744-44.032-41.984-78.848-31.744-105.984 10.752-27.136 28.672-49.664 44.544-69.632 31.232-38.4 46.592-59.904 29.696-98.816-12.8-28.672-34.816-49.152-66.56-60.928-20.992-8.192-38.4-9.728-43.008-9.728-7.68 0.512-49.664 6.144-77.824 43.52-29.184 38.4-35.84 97.28-19.968 176.128 20.48 100.864 104.448 221.184 229.888 331.264 51.2 44.544 106.496 84.992 156.672 113.664 52.224 30.208 87.04 40.96 102.4 41.472h3.584l3.584 1.024z"
											fill="#2E77ED" p-id="4849"></path>
										<path
											d="M752.64 553.984h-3.072c-16.896-1.536-29.184-16.384-27.648-33.28 5.632-58.88-7.168-105.984-37.376-140.288-52.736-59.392-142.336-62.464-143.36-62.464-16.896-0.512-30.208-14.336-29.696-31.232 0.512-16.896 14.336-30.208 31.232-29.696 4.608 0 117.248 4.096 187.392 82.944 41.984 47.104 59.392 110.08 52.224 186.88-1.024 14.848-14.336 27.136-29.696 27.136z"
											fill="#FFBB12" p-id="4850"></path>
										<path
											d="M913.92 511.488h-3.584c-16.896-2.048-28.672-17.408-26.624-34.304 11.776-95.744-7.68-172.544-57.344-227.84-95.744-106.496-273.408-104.448-274.944-104.448-16.896 0.512-30.72-13.312-31.232-30.208-0.512-16.896 13.312-30.72 30.208-31.232 2.048 0 52.224-1.024 116.736 13.824 37.888 8.704 73.216 20.992 104.448 36.352 39.936 19.456 73.728 44.544 100.864 74.752 62.464 69.12 87.04 162.304 72.704 276.48-2.56 15.36-15.872 26.624-31.232 26.624z"
											fill="#FFBB12" p-id="4851"></path>
									</svg>
									<span
										style="line-height:80rpx;font-weight: bold;color: darkgray;text-indent: 1rem;">联系方式：</span>
									<view>{{selectItem?.stuPhone}}</view>
								</view>
								<hr style="width: 90%;margin: auto;" />

								<view v-for="(item,index) in allQuestions" :key="index" style="margin-top: 40rpx;">

									<text style="color: darkgray;font-weight: bold;">问题{{index+1}}-{{item?.name}}?
									</text>

									<textarea
										style="border: 1rpx solid rgb(226,230,234);border-radius: 50rpx;padding: 20rpx;height: 220rpx;width: 100%;"
										placeholder="请输入问题" v-model="item.value"></textarea>

								</view>
							</view>

						</view>
					</view>
				</TnPopup>
			</view>
		</view>

	</view>
</template>

<style>
	.select-body {
		width: 1200px;
		height: 100%;
		margin: 0 auto;
		padding: 51px 0 51px 0;
		box-sizing: border-box;

	}

	.select-body .consultant-tabs {
		display: -webkit-box;
		display: -ms-flexbox;
		display: flex;
		-webkit-box-align: center;
		-ms-flex-align: center;
		align-items: center;
		height: 40px;
		margin-bottom: 30px;
	}

	.consultant-details-box {}

	.consultant-info-box {
		background: #fff;
		border-radius: 5px;
		width: 300px;
		margin-right: 30px;
		padding: 30px 20px;
		max-height: 500px;
		box-sizing: border-box;
	}

	.avatar-box {
		margin: 0 auto 12px;
		width: 128rpx;
		height: 128rpx;
		position: relative;
	}

	.cnUser-name {
		text-align: center;
		line-height: 25px;
		font-size: 18px;
		font-weight: 700;
		color: #333;
		margin-bottom: 6px;
	}

	.cnUser-phone,
	.cnUser-email {
		line-height: 20px;
		font-size: 14px;
		color: #333;
		margin-bottom: 2px;
		text-align: center;
	}

	.intro-content {
		background: #f4faff;
		border-radius: 5px;
		padding: 15px;
		width: 100%;
		box-sizing: border-box;
		color: #666;
		font-size: 12px;
		line-height: 20px;
		word-wrap: break-word;
	}

	.details-right {
		min-width: 30%;
		overflow: hidden;
		max-width: 870px;
		flex: 1;
		background: #fff;

	}

	.time-box {

		border-radius: 5px;

	}

	.details-year {
		height: 128rpx;
		line-height: 128rpx;
		border-bottom: 1px solid #edf2fa;
		padding-left: 30px;
		color: #333;
		font-size: 24px;
		font-weight: 700;
	}

	.scheduling-item {
		padding-top: 15px;
		padding-bottom: 5px;
		border-bottom: 1px solid #edf2fa;
		display: -webkit-box;
		display: -ms-flexbox;
		display: flex;
	}

	.scheduling-date {
		width: 50px;
		line-height: 22px;
		color: #333;
		font-size: 18px;
		font-weight: 700;
	}

	.date-scheduling {
		display: -webkit-box;
		display: -ms-flexbox;
		display: flex;
		-ms-flex-wrap: wrap;
		flex-wrap: wrap;
		-webkit-box-flex: 1;
		-ms-flex: 1;
		flex: 1;
	}
</style>
